<template>
  <div id="addTemplate">
    <el-form :model="form" ref="form" label-width="110px" inline label-suffix="：" v-loading="loading">
      <el-tabs v-model="active">
        <el-form-item label="模板名称" prop="name" :rules="rulesName">
          <el-input class="maxSelect" v-model="form.name"></el-input>
        </el-form-item>
        <el-tab-pane label="基础设置" lazy>
          <basic-setting v-model="form" ref="basicSetting" />
        </el-tab-pane>
        <el-tab-pane label="工资项">
          <wage-item ref="wageItem" />
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <div class="footer">
      <el-button @click="onClose">取消</el-button>
      <el-button type="primary" @click="onSave" :loading="loading">确认</el-button>
    </div>
  </div>
</template>
<script>
import { errorMessage } from "@/util/xc/utils";
import { mapState } from "vuex";
import basicSetting from "./components/basicSetting.vue"; // 基础设置
import wageItem from "./components/wageItem.vue"; // 工资项
import HandleSystem from "./components/standardFormula/handleSystem";
export default {
  name: "addTemplate",
  components: { basicSetting, wageItem },
  data() {
    return {
      active: 0,
      form: {
        name: "",
        taxType: 1,
        taxMonthType: 1
      },
      rulesName: { required: true, message: "请输入模板名称" },
      loading: false,
      allInfo: "",
      id: "",
      isSimple: false // 是否需要复杂修改
    };
  },
  computed: {
    ...mapState({
      tagList: state => state.tag.tagList,
      tagCurrent: state => state.tag.tagCurrent
    })
  },
  methods: {
    ...{
      closeCurrentTags() {
        // 关闭当前tags
        let item = this.tagCurrent;
        this.$store.commit("DEL_TAG", item);
      }
    },
    onClose() {
      this.closeCurrentTags();
      this.$router.replace({ name: "salaryTemplate" });
    },
    // 保存按钮 包括编辑
    ...{
      verify() {
        return new Promise((resolve, reject) => {
          this.$refs.form?.validate(valid => {
            if (valid) resolve();
            else reject();
          });
        });
      },
      async onSave() {
        try {
          this.loading = true;
          await this.verify();
          console.log(this.id, this.copy, !this.id || this.copy);

          if (!this.id || this.copy) await this.exeAdd();
          else await this.exeEdit();

          this.onClose();
        } catch (message) {
          if (typeof message === "string" && message) this.$message({ message, type: "warning" });
        } finally {
          this.loading = false;
        }
      },

      /** 添加 */
      async exeAdd() {
        const params = await this.getHandleData();
        console.log(params);
        // return Promise.reject();
        const { message = "添加成功" } = await this.$api.smartSalary.addSalaryTemplate(params).then(res => res.data);
        this.$message({ message, type: "success" });
      },

      /** 编辑 */
      async exeEdit() {
        const isSimple = this.$refs.basicSetting?.dataDiff() || this.$refs.wageItem?.dataDiff() || HandleSystem.diffArr();
        const params = await this.getHandleData(!isSimple);
        // console.log(isSimple, params);

        const { message = "编辑成功" } = isSimple ? await this.$api.smartSalary.editSalaryTemplateItems(params).then(res => res.data) : await this.$api.smartSalary.editSalaryTemplate(params).then(res => res.data);
        // return Promise.reject();
        this.$message({ message, type: "success" });
      },

      /**
       * 处理数据请求接口
       * simple: 简单数据
       */
      async getHandleData(simple = false) {
        try {
          const { id } = this;
          const { itemList, columnList } = await this.$refs.wageItem?.getData() || [];
          const { systemFormulas = [], systemFormulaTypes = [] } = HandleSystem.getParams();
          const basic = await this.$refs.basicSetting?.getData() || {};
          const { name } = this.form;
          const { subId, companyId } = basic;

          let data = {
            ...basic,
            name,
            departmentList: [],
            itemList: [],
            columnList: []
          };
          if (id) data.id = Number(id);
          if (!simple) {
            Object.assign(data, {
              departmentList: basic.departmentList,
              itemList: itemList.map(item => ({ ...item, subId, companyId })),
              columnList: columnList.map(item => ({
                ...item,
                subId,
                companyId
              })),
              systemFormulas: systemFormulas.map(n => ({ ...n, subId, companyId })),
              systemFormulaTypes: systemFormulaTypes.map(n => ({ ...n, subId, companyId }))
            });
          }
          return data;
        } catch (err) {
          errorMessage(err);
          return Promise.reject();
        }
      }
    },
    ...{
      async getSalaryTemplate(id, copy) {
        try {
          this.loading = true;
          this.id = id;
          this.copy = copy;
          const { data } = await this.$api.smartSalary.getSalaryTemplate({ id }).then(res => res.data);
          this.allInfo = data;
          const { systemFormulaTypes, systemFormulas } = data;
          HandleSystem.init(systemFormulaTypes, systemFormulas);
          console.log("获取数据", data, this.$refs);
          this.$refs.basicSetting.dataBackFill(data);
          const empty = copy ? { name: "" } : {};
          this.form = { ...data, ...empty };
          if(copy) data.departmentList = [];
          this.$refs.wageItem.dataBackFill(data);
          this.$nextTick(this.$refs.form?.clearValidate);
        } finally {
          this.loading = false;
        }
      },
      initData() {
        this.form = {
          name: "",
          taxType: 1,
          taxMonthType: 1
        },
        this.$nextTick(() => {
          HandleSystem.init();
          // this.$refs.basicSetting.initData();
          this.$refs.wageItem.initData();
            this.$refs.form?.clearValidate();
        });
      }
    }
  },
  async activated() {
    const { id, copy, random } = this.$route.query;
    if (random != this.random) {
      this.id = "";
      this.copy = "";
      if (id) await this.getSalaryTemplate(id, copy);
      else this.initData();
    }
    console.log(random, this.random, this.id, this.copy);
    this.random = random;
  },
  beforeRouteEnter(to, from, next) {
    const { copy, id } = to.query;
    const sign = copy ? "复制" : id ? "编辑" : "添加";
    to.meta.title = sign + "工资项模板";
    next();
  }
};
</script>
<style lang="less">
#addTemplate {
  overflow: hidden;
  display: flex;
  flex-direction: column;
  .content,
  .el-form {
    overflow: hidden;
    display: flex;
    flex-direction: column;
    flex: 1;
    .el-tabs,
    .el-tabs__content {
      overflow: hidden;
      display: flex;
      flex-direction: column;
      .el-tab-pane {
        display: flex;
        flex-direction: column;
        overflow: hidden;
      }
    }
  }
  .footer {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 70px;
    box-shadow: 0 -18px 19px -21px #ccc;
    z-index: 1;
  }
  .maxSelect {
    width: 200px;
  }
  .el-form {
    :deep( .el-form-item) {
      margin-right: 0;
    }
  }
}
</style>
